package com.dao;

import java.sql.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.model.Agent;
import com.model.Branch;
import com.model.Employee;
import com.service.BranchService;

@Repository("employeeDao")
public class EmployeeDaoImpl implements EmployeeDao{
	
	@Autowired
	private SessionFactory sessionFactory;
	@Autowired
	private BranchService branchService;
	
	public Session getSession()
	{
		return sessionFactory.getCurrentSession();
	}
	@Override
	public void add(String branch,Employee employee) {
		employee.setBranch(branchService.findByName(branch));
		getSession().save(employee);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Employee> getAll(int page) {
		return getSession().createCriteria(Employee.class) 
				.addOrder(Order.desc("employeeId"))
				.setFirstResult((page-1) * 5).setMaxResults(5).setFetchSize(5)
				.list(); 
				
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Employee> getAllForAdmin() {
		return (List<Employee>) getSession().createCriteria(Employee.class).list();	
	}

	@Override
	public Employee get(Integer id) {
		return (Employee)getSession().get(Employee.class, id);	
	}

	@Override
	public void delete(Integer id) {

		Employee employee= (Employee) getSession().get(Employee.class, id);
			getSession().delete(employee);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Employee> getByDate(Date from, Date to) {
		Criteria criteria = getSession().createCriteria(Employee.class);
		if (from != null) {
			criteria.add(Expression.ge("date",from));
		}
		if (to != null) {
			criteria.add(Expression.le("date",to));
		}
		
		return criteria.list();
	}

	@Override
	public int getNoOfRecords() {
		return ((Number) getSession().createQuery("select count(*) from Employee").uniqueResult()).intValue();
	}

	@SuppressWarnings("unchecked")
	public List<Employee> getAllForUser(String name) {
		return getSession().createCriteria(Employee.class)
				.createAlias("branch", "b")
				.add(Expression.eq("b.branchName",name))
				.list();
	}
}
